package com.ydj.framework.third.email;

import cn.hutool.core.io.resource.ResourceUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

@Slf4j
@Component
public class EmailManager {
    @Value("${app.email.appName}")
    String appName;

    @Value("${app.email.fromEmail}")
    String fromEmail;

    @Value("${app.email.password}")
    String password;

    @Value("${app.email.companyName}")
    String companyName;

    public void sendEmailVerifyCode(String toEmail, String verifyCode, int minute) {
        String title = String.format("【%s】邮箱验证码)", appName);
        String expiresMinutes = minute + "分钟";
        try {
            Session session = createSession();
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress(fromEmail));
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail));
            message.setSubject(title);

            String content = ResourceUtil.readUtf8Str("emailtemplate/SendEmailVerifyCode.template");
            content = content.replace("{{app_name}}", appName)
                    .replace("{{verify_code}}", verifyCode)
                    .replace("{{recipient_email}}", toEmail)
                    .replace("{{expires_minutes}}", expiresMinutes)
                    .replace("{{send_date}}", DateFormatUtils.format(System.currentTimeMillis(), "yyyy-MM-dd HH:mm:ss"))
                    .replace("{{year}}", "2025")
                    .replace("{{company_name}}", companyName);
            message.setContent(content, "text/html;charset=UTF-8");
            message.setHeader("Content-Type", "text/html;charset=UTF-8");
            message.setHeader("Content-Transfer-Encoding", "base64");

            Transport.send(message);

            log.info("【发送邮件】成功。发送邮箱验证码成功");
        } catch (MessagingException e) {
            log.error("【发送邮件】错误。", e);
        }
    }

    private Session createSession() {
        Properties props = new Properties();
        props.put("mail.transport.protocol", "smtp");
        props.put("mail.smtp.host", "smtp.163.com");   // 163 SMTP服务器
        props.put("mail.smtp.port", "465");            // SSL端口 465（推荐），也可用 25
        props.put("mail.smtp.auth", "true");           // 需要身份验证
        props.put("mail.smtp.ssl.enable", "true");     // 启用SSL
//        props.put("mail.debug", "true");               // 开启debug便于查看过程
//        props.setProperty("mail.debug.auth", "true");

        Session session = Session.getInstance(props, new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(fromEmail, password);
            }
        });
        return session;
    }
}
